#include<vector>
#include<pthread.h>
#include <semaphore.h>
#include<time.h>
#include<iostream>
using namespace std;

static int defaultnum=1;

template<class T>
class RingQueue
{
private:
    void P(sem_t& sem){
        sem_wait(&sem);
    }
    void V(sem_t& sem){
        sem_post(&sem);
    }
    void Lock(pthread_mutex_t& mutex)
    {
        pthread_mutex_lock(&mutex);
    }
    void Unlock(pthread_mutex_t& mutex)
    {
        pthread_mutex_unlock(&mutex);
    }

public:
    RingQueue(int num=defaultnum)
        :ringqueue_(num),c_step(0),p_step(0),cap_(num){
        sem_init(&data_sem, 0, 0);
        sem_init(&space_sem, 0, num);
        pthread_mutex_init(&c_mutex_,nullptr);
        pthread_mutex_init(&p_mutex_,nullptr);
    }
    void push(T& in)
    {
        P(space_sem);
        Lock(p_mutex_);
        ringqueue_[p_step]=in;
        p_step++;
        p_step%=cap_;
        Unlock(p_mutex_);
        V(data_sem);
    }
    void pop(T*out)
    {
        P(data_sem);
        Lock(c_mutex_);
        (*out) = ringqueue_[c_step];
        c_step++;
        c_step%=cap_;
        Unlock(c_mutex_);
        V(space_sem);
    }
    ~RingQueue()
    {
        pthread_mutex_destroy(&c_mutex_);
        pthread_mutex_destroy(&p_mutex_);
        sem_destroy(&data_sem);
        sem_destroy(&space_sem);
    }

private:
    vector<T>ringqueue_;
    int cap_;

    int c_step;//c走到哪里
    int p_step;//p走到哪里

    sem_t data_sem;//数据信号量
    sem_t space_sem;//空间信号量

    pthread_mutex_t c_mutex_;//c的锁
    pthread_mutex_t p_mutex_;//p的锁
};